<?php

namespace app\yue\home;

use think\Db;

class Rank extends Auth
{
    public function index()
    {
        $gid           = input('gid', 'GEK4O0XhYWG6YXMlZiw5xhA6X0zI');
        $order_by_rank = input('order_by_rank', true);

        $self         = model('yue_member')->find($this->uid);
        $group_member = model('yue_group_member');

        if ($self->rank and !$group_member->where(['uid' => $this->uid, 'openGid' => $gid])->count()) {
            $group_member->save(['uid' => $this->uid, 'openGid' => $gid]);
        }

        $order = $order_by_rank ? 'yue_member.rank desc' : 'win_rate desc';

        $list = Db::view('yue_member', '*, win/(win + lose) win_rate')
            ->view('yue_group_member', '*', 'yue_member.id = yue_group_member.uid')
            ->where('yue_group_member.openGid', $gid)
            ->order($order)
            ->select();
        
        $rank_num = 1;
        foreach ($list as &$v) {
        	$v['rank_num'] = $rank_num;
        	$v['rank'] = config('yue_rank')[$v['rank']];
        	if($v['uid'] == $this->uid){
        		$self = $v;
        	}
        	$rank_num ++;
        }
        unset($v);

        return json([
            'err'  => 0,
            'list' => $list,
            'self' => isset($self) ? $self : '',
            'gid'  => $gid,
            'msg'  => 'success',
        ]);

    }
}
